package com.lhl.blog.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;

import java.security.Key;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JwtUtils {
    //密钥
    public static final String secret = "jwt0v9zEAx1gq0PU1I1uvasMVYSxJl6SthwZrEh4cRA=";
    //生成安全密钥
    //根据字符串secret采用BASE64的编码方式生成一个key
    public static final Key key = Keys.hmacShaKeyFor(Decoders.
            BASE64.decode(secret));

    //设置token24小时过期
    private static final long expiration = 24 * 60 * 60 * 1000;

    //1、生成token
    public static String genToken( Map<String,Object> map){

        return Jwts.builder()
                .setClaims(map)
                .signWith(key)//设置签名
                .setIssuedAt(new Date())//设置签发日期
                .setExpiration(new Date(System.currentTimeMillis()+expiration))//设置签名过期时间
                .compact();
    }


    //2、校验token
    public static Claims parseJwt( String token){
        if (!StringUtils.hasLength(token)){
            return null;
        }

        //jwt解析器
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims body = null;
        try {
            body = build.parseClaimsJws(token).getBody();
            return body;
        }catch (ExpiredJwtException e){
            log.error("token过期，token:{}",token);
        }catch (SignatureException e){
            log.error("签名不匹配，token：{}",token);
        }catch (Exception e) {
            log.error("token解析失败，token：{}",token);
        }
        return null;
    }

}















